/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

 import {debounce} from './common/util'
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, Linking, View, Alert, TextInput, Button, NativeModules} from 'react-native';
import UsbSerialDevice from './usb';
const UsbSerialModule = NativeModules.UsbSerial;

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {
  constructor(props) {
    super(props)
    this.state = {
      phoneNumber: '',
      showErr: false,
      testWords: '',
      usbText: '',
      usbData: '',
      resData: ''
    }
  }
  fillterObj =(obj) => {
    var arr = []
    for(var key in obj) {
      arr.push(obj[key])
    }
    return arr
  }
  getDeviceListAsync =() => {
    this.setState({
      usbText:  UsbSerialModule.getDeviceListAsync()[0]
    },() => {
      // let usb = this.fillterObj(this.state.usbText)[0] // 40接口为0
      // let usb = {"_40": 0}
      
      if(this.state.usbText) {
        this.openDeviceAsync(this.state.usbText)
      }
    })

    // return UsbSerialModule.getDeviceListAsync();
  }
  openDeviceAsync = (deviceObject) => {
    return UsbSerialModule.openDeviceAsync(deviceObject).then((usbSerialDevNativeObject) => {
      this.setState({
        usbData: JSON.stringify(UsbSerialDevice(UsbSerialModule, usbSerialDevNativeObject))
      })
      this.setState({
        resData : usbSerialDevNativeObject
      })
        // return new UsbSerialDevice(UsbSerialModule, usbSerialDevNativeObject);
    }).catch((err) => {
      this.setState({
        usbData: JSON.stringify(err)
      })
    });
}
  componentDidMount() {
    // this.openDeviceAsync()
  }
  // 还是得使用箭头函数写法，不然获取不到this，就无法使用相关的react语法
  testHttp =()=> {
    var that = this
    fetch('http://192.168.1.73:2500').then((response) => response.json())
    .then((responseJSON) => {
      this.setState({
        testWords: responseJSON.name
      })
    })
  }
  
  openUrl = () => {
    Linking.openURL(url="https://www.baidu.com").catch(err => console.error('An error occurred', err));
  }

  sendMessage = () => {
    // Linking.canOpenURL('').then(supported => {
    //   if (supported) {
        if(Platform.OS === 'ios') {
          Linking.openURL("sms:" + this.state.phoneNumber + "&body=短信内容");
        } else {
          Linking.openURL("sms:"+ this.state.phoneNumber + "?body=短信内容");
        }
  //     } else {
  //        console.log('无法打开该URI: ' + this.props.url);
  //     }
  //  })
  }

  validatePhone = (phone) => {
    this.setState({
      phoneNumber: phone,
    })
    if((/^1(3|4|5|7|8)\d{9}$/.test(phone))){
      this.setState({
        showErr: false
      })
    } else {
      this.setState({
        showErr: true
      })
    }
    
  }

  render() {
    return (
      <View style={styles.container}>
      <View style={{ flexDirection: 'row',height:100}}>
        <View style={{flex: 0.2, paddingLeft:5, paddingTop: 6}}>
          <Text style={styles.messageText}>输入短信：</Text>
        </View>
        <View style={{flex: 0.5}}>
          <TextInput style={[styles.messageInput,{height: 40}]}
          placeholder='请输入手机号！'
          onChangeText={
            (phone) => this.validatePhone(phone)
          }
          value={this.state.phoneNumber}
          />
          {
            this.state.showErr ? <Text style={{color: 'red'}}>{'请输入正确的手机号！'}</Text> : <Text>{""}</Text>
          }
        </View>
        <View style={{flex: 0.2}}>
          <Button style={styles.msgBtn} disabled={this.state.showErr} onPress={this.sendMessage} title="发送"></Button>
        </View>
      </View>
      <View>
        <Button onPress={this.testHttp} title="发起网络请求" />
        <Text>
          {this.state.testWords}
        </Text>
      </View>

      
       <View>
       <Button onPress={this.getDeviceListAsync} title="usbBtn" />
        <Text>
          {"usb驱动列表   "+this.state.usbText}
        </Text>
        <Text>
          {"usb的返回参数    "+ this.state.resData}
        </Text>
        <Text>
          {"usb打开后      "+this.state.usbData}
        </Text>
       </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    borderStyle: 'solid',
    borderWidth: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  buttonText: {

  },
  msgBtn: {
    height: 50,
    color: 'red',
    width: 100
  },
  messageText: {
    color:'red',
    width: 100,
  },
  messageInput: {
    borderWidth:1,
    borderStyle: 'solid',
    width: 200,
  },  
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
